package org.springblade.modules.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.admin.service.BuildingService;
import org.springblade.modules.admin.service.IEventMessagePushService;
import org.springblade.modules.admin.entity.AlarmEvent;
import org.springblade.modules.admin.mapper.AlarmEventMapper;
import org.springblade.modules.admin.service.AlarmEventService;
import org.springblade.modules.admin.vo.AlarmEventAdminVO;
import org.springblade.modules.admin.vo.AlarmEventVO;
import org.springblade.modules.admin.vo.EstateUserInfoVO;
import org.springblade.modules.admin.vo.EventMessagePushVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AlarmEventServiceImpl extends BaseServiceImpl<AlarmEventMapper, AlarmEvent> implements AlarmEventService {

	@Autowired
	private IEventMessagePushService eventMessagePushService;

	@Autowired
	private BuildingService buildingService;

	@Override
	public AlarmEventVO getAlarmEventDetailById(Long id) {
		return baseMapper.getAlarmEventDetailById(id);
	}

	@Override
	public IPage<AlarmEventVO> selectAlarmEventAdminPage(IPage<AlarmEventVO> page, AlarmEventAdminVO alarmEventAdminVO) {
		return page.setRecords(baseMapper.selectEventAdminPage(page, alarmEventAdminVO));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean eventConfirm(AlarmEventVO alarmEventVO) {
		AlarmEvent alarmEvent = Objects.requireNonNull(BeanUtil.copy(alarmEventVO, AlarmEvent.class));
		alarmEvent.setStatus(EVENT_CONFIRM_STATUS);
		if (baseMapper.updateById(alarmEvent) > 0) {
			//封装发送消息数据
			EventMessagePushVO messageData = new EventMessagePushVO();
			messageData.setBuildingName(alarmEventVO.getBuildingName());
			messageData.setElevatorAddress(alarmEventVO.getElevatorAddress());
			messageData.setRemark(alarmEventVO.getEventMsg());
			messageData.setTime(DateUtil.format(alarmEvent.getEventTimeStamp(),"yyyy-MM-dd HH:mm:ss"));
			//物业人员信息
			List<EstateUserInfoVO> userInfos = buildingService.selectEstateUserInfoByBuildingId(alarmEvent.getBuildingId());
			messageData.setPhone(userInfos.stream().map(t -> t.getPhone()).filter(Objects::nonNull).collect(Collectors.joining(",")));
			messageData.setOpenid(userInfos.stream().map(t -> t.getOpenid()).filter(Objects::nonNull).collect(Collectors.joining(",")));
			eventMessagePushService.sendWeiXiMessage(messageData);
			eventMessagePushService.sendSms(messageData);
			return true;
		}
		return false;
	}
}

